package top.withwings.bonus.bonus.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.withwings.bonus.bonus.pojo.bonus.rule.BonusRule;
import top.withwings.bonus.bonus.pojo.bonus.rule.ExpirationCloseBonusRule;
import top.withwings.bonus.bonus.pojo.bonus.rule.HighPriceBonusRule;
import top.withwings.bonus.bonus.repo.BonusRuleRepo;
import top.withwings.bonus.bonus.repo.ExpirationCloseAttachmentRepo;
import top.withwings.bonus.bonus.repo.HighPriceAttachmentRepo;

@Service
public class RuleAttachmentService {

    @Autowired
    private BonusRuleRepo bonusRuleRepo;

    @Autowired
    private ExpirationCloseAttachmentRepo expirationCloseAttachmentRepo;

    @Autowired
    private HighPriceAttachmentRepo highPriceAttachmentRepo;

    @Transactional
    public void attachRule(int ruleId, int... goodIds) {
        BonusRule rule = bonusRuleRepo.findById(ruleId);
        if (rule == null) {
            throw new IllegalArgumentException("无效的规则ID");
        }
        detachRule(rule.getType(), goodIds);
        if (rule.getType().equalsIgnoreCase(HighPriceBonusRule.TYPE)) {
            highPriceAttachmentRepo.attach(ruleId, goodIds);
        } else if (rule.getType().equalsIgnoreCase(ExpirationCloseBonusRule.TYPE)) {
            expirationCloseAttachmentRepo.attach(ruleId, goodIds);
        }

    }


    @Transactional
    public void detachRule(String type, int... goodIds) {
        if (type.equalsIgnoreCase(HighPriceBonusRule.TYPE)) {
            highPriceAttachmentRepo.detach(goodIds);
        } else if (type.equalsIgnoreCase(ExpirationCloseBonusRule.TYPE)) {
            expirationCloseAttachmentRepo.detach(goodIds);
        }


    }

    public HighPriceBonusRule findHighPriceRule(int goodId) {

        Integer ruleId = highPriceAttachmentRepo.findByGood(goodId);
        if (ruleId == null) {
            return null;
        } else {
            return (HighPriceBonusRule) bonusRuleRepo.findById(ruleId);
        }

    }

    public ExpirationCloseBonusRule findExpirationCloseRule(int goodId) {

        Integer ruleId = expirationCloseAttachmentRepo.findByGood(goodId);
        if (ruleId == null) {
            return null;
        } else {
            return (ExpirationCloseBonusRule) bonusRuleRepo.findById(ruleId);
        }
    }


}